from flask import Flask, render_template
from flask_cors import CORS
from flasgger import Swagger
from api.vector_db import vector_bp
from api.document_api import document_bp
from api.knowledge_api import knowledge_bp
from api.segment_api import segment_bp
from api.chat_api import chat_bp
from api.task_api import task_bp  
from api.indicator_routes import indicator_bp
from api.sync_api import sync_bp  # 导入同步API蓝图
from api.model_calls import model_calls_bp
from api.system_prompt_api import system_prompt_bp
from api.session_api import session_bp
from models import db 
from config import DB_CONFIG
import yaml
import os
import logging

def create_app():
    # 设置日志级别
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s %(levelname)s: %(message)s'
    )
    
    # 创建 Flask 应用实例
    app = Flask(__name__,
                static_url_path='',
                template_folder='templates',
                static_folder='static')
    
    # 启用调试模式
    app.config['DEBUG'] = False

    app.config['JSON_AS_ASCII'] = False
    app.json.ensure_ascii = False

    # 加载配置
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_CONFIG['URI']
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = DB_CONFIG['TRACK_MODIFICATIONS']
    
    # 初始化扩展及跨域设置，支持所有路由和来源，同时可支持凭据传递
    CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)
    db.init_app(app)

    # Swagger配置
    with open('openapi.yaml', 'r', encoding='utf-8') as f:
        template = yaml.safe_load(f)
    Swagger(app, template=template)
    
    # 注册蓝图
    app.register_blueprint(vector_bp, url_prefix='/api/vector')
    app.register_blueprint(document_bp, url_prefix='/api/documents')
    app.register_blueprint(knowledge_bp, url_prefix='/api/knowledges')
    app.register_blueprint(segment_bp, url_prefix='/api/segments')
    app.register_blueprint(chat_bp, url_prefix='/api')
    app.register_blueprint(task_bp, url_prefix='/api/tasks')
    app.register_blueprint(indicator_bp, url_prefix='/api/indicators')
    app.register_blueprint(sync_bp, url_prefix='/api/sync')
    app.register_blueprint(model_calls_bp, url_prefix='/api')
    app.register_blueprint(session_bp, url_prefix='/api')
    app.register_blueprint(system_prompt_bp, url_prefix='/api')

    # 注册路由
    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/documents')
    def document_list():
        return render_template('documents.html')
    
    @app.route('/segments')
    def segment_list():
        return render_template('segments.html')

    @app.route('/collection/<collection_name>')
    def collection_page(collection_name):
        return render_template('collection.html', collection_name=collection_name)

    @app.route('/chat')
    def chat_page():
        return render_template('chat.html')

    @app.route('/test')
    def test():
        return "Server is running!"

    @app.route('/sync')
    def sync():
        return render_template('sync.html')  # 添加同步页面路由
    
    @app.route("/model-calls")
    def model_calls_page():
        return render_template('model-calls.html')
        
    return app

# 创建应用实例
app = create_app()

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host='0.0.0.0', port=5000, debug=False, use_reloader=True)